package com.muqi.app.im.ui;

import java.io.File;
import java.io.FileOutputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.easeui.ui.EaseChatFragment;
import com.easemob.easeui.ui.EaseChatFragment.EaseChatFragmentListener;
import com.easemob.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.easemob.easeui.widget.emojicon.EaseEmojiconMenu;
import com.easemob.util.PathUtil;
import com.muqi.app.im.domain.EmojiconExampleGroupData;
import com.muqi.app.im.qmain.Constant;
import com.muqi.app.im.qmain.ContextMenuActivity;
import com.muqi.app.project.contants.MContants;
import com.muqi.app.qlearn.ui.UserHomepagerActivity;
import com.muqi.app.sharepreference.SharePreferenceUtil;

public class ChatFragment extends EaseChatFragment implements EaseChatFragmentListener {
    //避免和基类定义的常量可能发生的冲突，常量从11开始定义
    private static final int ITEM_VIDEO = 11;
    private static final int ITEM_FILE = 12;
    private static final int ITEM_VOICE_CALL = 13;
    private static final int ITEM_VIDEO_CALL = 14;
    
    private static final int REQUEST_CODE_SELECT_VIDEO = 11;
    private static final int REQUEST_CODE_SELECT_FILE = 12;
    //private static final int REQUEST_CODE_GROUP_DETAIL = 13;
    private static final int REQUEST_CODE_CONTEXT_MENU = 14;
    
    public static final int MESSAGE_TYPE_SENT_VOICE_CALL = 1;
    public static final int MESSAGE_TYPE_RECV_VOICE_CALL = 2;
    public static final int MESSAGE_TYPE_SENT_VIDEO_CALL = 3; 
    public static final int MESSAGE_TYPE_RECV_VIDEO_CALL = 4;
    
    /** user登录配置 */
	public SharePreferenceUtil mSpUtil;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    	mSpUtil = new SharePreferenceUtil(getActivity(), MContants.UserLogin);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void setUpView() {
        setChatFragmentListener(this);
        if (chatType == Constant.CHATTYPE_SINGLE) { 
           
        }
        super.setUpView();
       // ((EaseEmojiconMenu)inputMenu.getEmojiconMenu()).addEmojiconGroup(EmojiconExampleGroupData.getData());
    }
    
    @Override
    protected void registerExtendMenuItem() {
        //不覆盖基类已经注册的item,item点击listener沿用基类的
        super.registerExtendMenuItem();
    }
    
    @SuppressWarnings("deprecation")
	@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
            switch (resultCode) {
            case ContextMenuActivity.RESULT_CODE_COPY: // 复制消息
                clipboard.setText(((TextMessageBody) contextMenuMessage.getBody()).getMessage());
                break;
            case ContextMenuActivity.RESULT_CODE_DELETE: // 删除消息
                conversation.removeMessage(contextMenuMessage.getMsgId());
                messageList.refresh();
                break;
            case ContextMenuActivity.RESULT_CODE_FORWARD: // 转发消息
//                Intent intent = new Intent(getActivity(), ForwardMessageActivity.class);
//                intent.putExtra("forward_msg_id", contextMenuMessage.getMsgId());
//                startActivity(intent);
                break;
            default:
                break;
            }
        }
        if(resultCode == Activity.RESULT_OK){
            switch (requestCode) {
            case REQUEST_CODE_SELECT_VIDEO: //发送选中的视频
                if (data != null) {
                    int duration = data.getIntExtra("dur", 0);
                    String videoPath = data.getStringExtra("path");
                    File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
                    try {
                        FileOutputStream fos = new FileOutputStream(file);
                        Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                        ThumbBitmap.compress(CompressFormat.JPEG, 100, fos);
                        fos.close();
                        sendVideoMessage(videoPath, file.getAbsolutePath(), duration);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case REQUEST_CODE_SELECT_FILE: //发送选中的文件
                if (data != null) {
                    Uri uri = data.getData();    
                    if (uri != null) {
                        sendFileByUri(uri);
                    }
                }
                break;
            default:
                break;
            }
        }
    }
    
    @Override
    public void onSetMessageAttributes(EMMessage message) {
        
    }
    
    @Override
    public void onEnterToChatDetails() {
		if (chatType == Constant.CHATTYPE_SINGLE) {
			Intent intent = new Intent();
			intent.putExtra(UserHomepagerActivity.IM_OR_MOBILE_OR_USERID,toChatUsername);
			intent.setClass(getActivity(), UserHomepagerActivity.class);
			startActivity(intent);
		}else{
			Intent intent = new Intent();
			intent.putExtra("groupId",toChatUsername);
			intent.setClass(getActivity(), GroupDetailsActivity.class);
			startActivity(intent);
		}
    }

    @Override
    public void onAvatarClick(String username) {
        //头像点击事件
    	Intent intent = new Intent();
		intent.putExtra(UserHomepagerActivity.IM_OR_MOBILE_OR_USERID,username);
		intent.setClass(getActivity(), UserHomepagerActivity.class);
		startActivity(intent);
    }
    
    @Override
    public boolean onMessageBubbleClick(EMMessage message) {
        //消息框点击事件，demo这里不做覆盖，如需覆盖，return true
        return false;
    }

    @Override
    public void onMessageBubbleLongClick(EMMessage message) {
        //消息框长按
        startActivityForResult((new Intent(getActivity(), ContextMenuActivity.class)).putExtra("message",message),REQUEST_CODE_CONTEXT_MENU);
    }

    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
        switch (itemId) {
        case ITEM_VIDEO: //视频
            break;
        case ITEM_FILE: //一般文件
            selectFileFromLocal();
            break;
        case ITEM_VOICE_CALL: //音频通话
            break;
        case ITEM_VIDEO_CALL: //视频通话
            break;
        default:
            break;
        }
        //不覆盖已有的点击事件
        return false;
    }

	/**
     * 选择文件
     */
    protected void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) { //19以后这个api不可用，demo这里简单处理成图库选择图片
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }

	@Override
	public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
		return null;
	}
}
